from django.db import models
import datetime
from ximport.models import UploadFile

TRADINGLIST_TYPES = (
    (u"L", u"Long (buy)")
    , (u"S", u"Short (sell)")
    , (u"E", u"Sell short")
    , (u"C", u"Buy to cover")
                     )

class TradinglistNorm(models.Model):
    entry_type = models.CharField(max_length = 2, choices = TRADINGLIST_TYPES)
    entry_date = models.DateField(default = datetime.datetime.now())
    #entry_time
#    entry_price = models.IntegerField(default = 0)
    entry_price = models.FloatField()
    exit_type = models.CharField(max_length = 2, choices = TRADINGLIST_TYPES)
    exit_date = models.DateField()
    #exit_time
    exit_price = models.FloatField()

    csv_file_id = models.ForeignKey(UploadFile)
    
    def set_entry_type(self, v):
        ar_values = {u"Long": "L", u"Short": "S", u"Sell": "E", "Buy": "C"}
        t = ""
        try:
            t = ar_values[v]
        except KeyError:
            print "Tradinglist does not know entry type [%s]!" % v
        
        self.entry_type = t

    def set_exit_type(self, v):
        ar_values = {u"LExit": "L", u"SExit": "S"}
        t = ""
        try:
            t = ar_values[v]
        except KeyError:
            print "Tradinglist does not know exit type [%s]!" % v
        
        self.exit_type = t

    def get_month_nr(self):
        return self.entry_date.month
#        return "%s%s" % (self.entry_date[2:4], self.entry_date[5:7])

    def get_is_profit(self):
        return self.get_profit() >= 0

    def get_profit(self):
        if self.entry_type == "L" or self.entry_type == "Buy" or self.entry_type == "C":
            return float(self.exit_price) - float(self.entry_price)
        elif self.entry_type == "S" or self.entry_type == "Sell" or self.entry_type == "E":
            return float(self.entry_price) - float(self.exit_price)
        print "Entry type: %s" % self.entry_type
        return "X"

    def entry_type_name(self):
        ar_names = {"L": "Long", "S": "Short (sell)", "E": "Sell short", "C": "Buy to cover"}
        return "%s" % ar_names[self.entry_type]

    def exit_type_name(self):
        ar_names = {"L": "Long", "S": "Short (sell)", "E": "Sell short", "C": "Buy to cover"}
        return "%s" % ar_names[self.exit_type]

    def __unicode__(self):
        return "%s %s %d %s %s %d)" % (self.entry_type_name(), self.entry_date, self.entry_price, self.exit_type_name(), self.exit_date, self.exit_price)
